<template>
  <div class="vehicle-form-page">
    <!-- 固定头部 -->
    <div class="page-header-fixed">
      <div class="header-left">
        <a class="back-link" @click="handleBack">
          <ArrowLeftOutlined />
          <span>返回车辆列表</span>
        </a>
        <h2>{{ isEdit ? "编辑车辆" : "新增车辆" }}</h2>
      </div>
      <div class="header-actions">
        <a-space>
          <a-button @click="handleBack">取消</a-button>
          <a-button type="primary" :loading="submitting" @click="handleSubmit">
            保存
          </a-button>
        </a-space>
      </div>
    </div>

    <!-- 可滚动内容区 -->
    <div class="page-content">
      <a-card class="form-card">
        <a-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <!-- 基本信息 -->
          <div class="form-section">
            <div class="section-header">
              <span class="section-title">基本信息</span>
            </div>

            <a-form-item label="车牌号" name="plateNumber">
              <a-input
                v-model:value="formData.plateNumber"
                placeholder="请输入车牌号，如：京A12345"
                :disabled="isEdit"
              />
            </a-form-item>

            <a-form-item label="车辆类型" name="vehicleType">
              <a-select
                v-model:value="formData.vehicleType"
                placeholder="请选择车辆类型"
              >
                <a-select-option
                  v-for="item in vehicleTypes"
                  :key="item.dictCode"
                  :value="item.dictCode"
                >
                  {{ item.dictLabel }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="车辆来源" name="vehicleSource">
              <a-radio-group v-model:value="formData.vehicleSource">
                <a-radio value="COMPANY">公司车</a-radio>
                <a-radio value="TEMP">临时车</a-radio>
              </a-radio-group>
            </a-form-item>

            <a-form-item label="品牌型号">
              <a-input
                v-model:value="formData.brandModel"
                placeholder="请输入品牌型号"
              />
            </a-form-item>
          </div>

          <!-- 性能参数 -->
          <div class="form-section">
            <div class="section-header">
              <span class="section-title">性能参数</span>
            </div>

            <a-form-item label="载重" name="loadCapacity">
              <a-input-number
                v-model:value="formData.loadCapacity"
                :min="0.01"
                :precision="2"
                style="width: 100%"
                placeholder="请输入载重"
              >
                <template #addonAfter>吨</template>
              </a-input-number>
            </a-form-item>

            <a-form-item label="容积">
              <a-input-number
                v-model:value="formData.volumeCapacity"
                :min="0.01"
                :precision="2"
                style="width: 100%"
                placeholder="请输入容积（可选）"
              >
                <template #addonAfter>m³</template>
              </a-input-number>
            </a-form-item>
          </div>

          <!-- 证件信息 -->
          <div class="form-section">
            <div class="section-header">
              <span class="section-title">证件信息</span>
            </div>

            <a-form-item label="购买日期">
              <a-date-picker
                v-model:value="formData.purchaseDate"
                format="YYYY-MM-DD"
                style="width: 100%"
                placeholder="请选择购买日期"
              />
            </a-form-item>

            <a-form-item label="保险到期" name="insuranceExpireDate">
              <a-date-picker
                v-model:value="formData.insuranceExpireDate"
                format="YYYY-MM-DD"
                style="width: 100%"
                placeholder="请选择保险到期日期"
              />
            </a-form-item>

            <a-form-item label="年检到期" name="inspectionExpireDate">
              <a-date-picker
                v-model:value="formData.inspectionExpireDate"
                format="YYYY-MM-DD"
                style="width: 100%"
                placeholder="请选择年检到期日期"
              />
            </a-form-item>
          </div>

          <!-- 车主信息 -->
          <div class="form-section">
            <div class="section-header">
              <span class="section-title">车主信息</span>
            </div>

            <a-form-item label="车主姓名" name="ownerName">
              <a-input
                v-model:value="formData.ownerName"
                placeholder="请输入车主姓名"
              />
            </a-form-item>

            <a-form-item label="联系电话" name="ownerPhone">
              <a-input
                v-model:value="formData.ownerPhone"
                placeholder="请输入车主联系电话"
              />
            </a-form-item>

            <a-form-item label="身份证号">
              <a-input
                v-model:value="formData.ownerIdCard"
                placeholder="请输入车主身份证号"
                :maxlength="18"
              />
            </a-form-item>

            <a-form-item label="驾驶证号">
              <a-input
                v-model:value="formData.ownerLicenseNumber"
                placeholder="请输入车主驾驶证号"
              />
            </a-form-item>

            <a-form-item label="驾驶证类型">
              <a-select
                v-model:value="formData.ownerLicenseType"
                placeholder="请选择驾驶证类型"
              >
                <a-select-option value="A1">A1 - 大型客车</a-select-option>
                <a-select-option value="A2">A2 - 牵引车</a-select-option>
                <a-select-option value="A3">A3 - 城市公交车</a-select-option>
                <a-select-option value="B1">B1 - 中型客车</a-select-option>
                <a-select-option value="B2">B2 - 大型货车</a-select-option>
                <a-select-option value="C1">C1 - 小型汽车</a-select-option>
                <a-select-option value="C2"
                  >C2 - 小型自动挡汽车</a-select-option
                >
              </a-select>
            </a-form-item>

            <a-form-item label="驾驶证到期">
              <a-date-picker
                v-model:value="formData.ownerLicenseExpireDate"
                format="YYYY-MM-DD"
                style="width: 100%"
                placeholder="请选择驾驶证到期日期"
              />
            </a-form-item>

            <a-form-item label="车主地址">
              <a-textarea
                v-model:value="formData.ownerAddress"
                placeholder="请输入车主地址"
                :rows="2"
                :maxlength="200"
              />
            </a-form-item>
          </div>

          <!-- 其他信息 -->
          <div class="form-section">
            <div class="section-title">其他信息</div>

            <a-form-item label="车辆状态">
              <a-radio-group v-model:value="formData.vehicleStatus">
                <a-radio
                  v-for="item in vehicleStatuses"
                  :key="item.dictCode"
                  :value="item.dictCode"
                >
                  {{ item.dictLabel }}
                </a-radio>
              </a-radio-group>
            </a-form-item>

            <a-form-item label="备注">
              <a-textarea
                v-model:value="formData.remark"
                placeholder="请输入备注信息"
                :rows="3"
                :maxlength="500"
                show-count
              />
            </a-form-item>
          </div>

          <!-- 提交按钮 -->
          <a-form-item :wrapper-col="{ offset: 6, span: 16 }">
            <a-space size="large">
              <a-button
                type="primary"
                :loading="submitting"
                @click="handleSubmit"
              >
                {{ isEdit ? "保存修改" : "保存车辆" }}
              </a-button>
              <a-button @click="handleBack">取消</a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter, useRoute } from "vue-router";
import { message } from "ant-design-vue";
import { ArrowLeftOutlined } from "@ant-design/icons-vue";
import {
  createVehicle,
  updateVehicle,
  getVehicleById,
} from "@/api/tenant/vehicle";
import { getDictionaryByType } from "@/api/tenant/dictionary";
import type { VehicleFormData } from "@/types/vehicle";
import type { Dictionary } from "@/types/dictionary";
import type { Dayjs } from "dayjs";
import dayjs from "dayjs";

const router = useRouter();
const route = useRoute();

const isEdit = computed(() => route.name === "VehicleEdit");

const formData = reactive<
  Omit<
    VehicleFormData,
    | "purchaseDate"
    | "insuranceExpireDate"
    | "inspectionExpireDate"
    | "ownerLicenseExpireDate"
  > & {
    purchaseDate?: Dayjs;
    insuranceExpireDate?: Dayjs;
    inspectionExpireDate?: Dayjs;
    ownerLicenseExpireDate?: Dayjs;
  }
>({
  plateNumber: "",
  vehicleType: "VAN",
  vehicleSource: "COMPANY",
  brandModel: "",
  loadCapacity: 0,
  volumeCapacity: undefined,
  purchaseDate: undefined,
  insuranceExpireDate: undefined,
  inspectionExpireDate: undefined,
  vehicleStatus: "AVAILABLE",
  remark: "",
  // 车主信息
  ownerName: "",
  ownerPhone: "",
  ownerIdCard: "",
  ownerLicenseNumber: "",
  ownerLicenseType: undefined,
  ownerLicenseExpireDate: undefined,
  ownerAddress: "",
});

// 字典数据
const vehicleTypes = ref<Dictionary[]>([]);
const vehicleStatuses = ref<Dictionary[]>([]);

const rules = {
  plateNumber: [{ required: true, message: "请输入车牌号" }],
  vehicleType: [{ required: true, message: "请选择车辆类型" }],
  vehicleSource: [{ required: true, message: "请选择车辆来源" }],
  loadCapacity: [{ required: true, message: "请输入载重" }],
  insuranceExpireDate: [{ required: true, message: "请选择保险到期日期" }],
  inspectionExpireDate: [{ required: true, message: "请选择年检到期日期" }],
  ownerName: [{ required: true, message: "请输入车主姓名" }],
  ownerPhone: [
    { required: true, message: "请输入车主联系电话" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
};

const formRef = ref();
const submitting = ref(false);

// 获取车辆详情（编辑时）
const fetchVehicleDetail = async () => {
  const id = Number(route.params.id);
  if (!id) return;

  try {
    const response = await getVehicleById(id);
    const vehicle = response.data as any;

    Object.assign(formData, {
      ...vehicle,
      purchaseDate: vehicle.purchaseDate
        ? dayjs(vehicle.purchaseDate)
        : undefined,
      insuranceExpireDate: vehicle.insuranceExpireDate
        ? dayjs(vehicle.insuranceExpireDate)
        : undefined,
      inspectionExpireDate: vehicle.inspectionExpireDate
        ? dayjs(vehicle.inspectionExpireDate)
        : undefined,
      ownerLicenseExpireDate: vehicle.ownerLicenseExpireDate
        ? dayjs(vehicle.ownerLicenseExpireDate)
        : undefined,
    });
  } catch (error: any) {
    console.error("获取车辆详情失败:", error);
  }
};

// 提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    submitting.value = true;

    const submitData: any = {
      plateNumber: formData.plateNumber,
      vehicleType: formData.vehicleType,
      vehicleSource: formData.vehicleSource,
      brandModel: formData.brandModel,
      loadCapacity: formData.loadCapacity,
      volumeCapacity: formData.volumeCapacity,
      purchaseDate: formData.purchaseDate
        ? formData.purchaseDate.format("YYYY-MM-DD")
        : undefined,
      insuranceExpireDate: formData.insuranceExpireDate!.format("YYYY-MM-DD"),
      inspectionExpireDate: formData.inspectionExpireDate!.format("YYYY-MM-DD"),
      vehicleStatus: formData.vehicleStatus,
      remark: formData.remark,
      // 车主信息
      ownerName: formData.ownerName,
      ownerPhone: formData.ownerPhone,
      ownerIdCard: formData.ownerIdCard,
      ownerLicenseNumber: formData.ownerLicenseNumber,
      ownerLicenseType: formData.ownerLicenseType,
      ownerLicenseExpireDate: formData.ownerLicenseExpireDate
        ? formData.ownerLicenseExpireDate.format("YYYY-MM-DD")
        : undefined,
      ownerAddress: formData.ownerAddress,
    };

    if (isEdit.value) {
      await updateVehicle(Number(route.params.id), submitData);
      message.success("车辆更新成功");
    } else {
      await createVehicle(submitData);
      message.success("车辆创建成功");
    }

    router.push("/tenant/vehicle");
  } catch (error: any) {
    console.error("保存车辆失败:", error);
    if (error.message && error.message !== "Error") {
      message.error(error.message);
    }
  } finally {
    submitting.value = false;
  }
};

// 返回
const handleBack = () => {
  router.push("/tenant/vehicle");
};

// 加载字典数据
const loadDictionaries = async () => {
  try {
    const [typesRes, statusesRes] = await Promise.all([
      getDictionaryByType("VEHICLE_TYPE"),
      getDictionaryByType("VEHICLE_STATUS"),
    ]);
    vehicleTypes.value = (typesRes.data || []) as unknown as Dictionary[];
    vehicleStatuses.value = (statusesRes.data || []) as unknown as Dictionary[];
  } catch (error) {
    console.error("加载字典失败:", error);
  }
};

// 初始化
onMounted(() => {
  loadDictionaries();
  if (isEdit.value) {
    fetchVehicleDetail();
  }
});
</script>

<style scoped>
.vehicle-form-page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.page-header-fixed {
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  background: #fff;
  padding-bottom: 16px;
  margin-bottom: 16px;
  border-bottom: 1px solid var(--border-color);
}

.header-left {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.back-link {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: var(--text-secondary);
  cursor: pointer;
  transition: color var(--transition-fast);
}

.back-link:hover {
  color: var(--primary-color);
}

.page-header-fixed h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-content {
  flex: 1;
  overflow: auto;
  padding: 0 16px 16px;
}

.form-card {
  max-width: 960px;
  border: none;
  box-shadow: var(--shadow-card);
}

::deep(.form-card .ant-card-body) {
  padding: 28px;
}

.form-section {
  margin-bottom: 32px;
}

.form-section:last-of-type {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.section-title {
  position: relative;
  padding-left: 12px;
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.section-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 2px;
  bottom: 2px;
  width: 4px;
  border-radius: 4px;
  background: var(--primary-color);
}

::deep(.ant-form-item) {
  margin-bottom: 20px;
}

::deep(.ant-form-item-label > label) {
  font-weight: 500;
  color: var(--text-primary);
}

@media (max-width: 992px) {
  .page-header-fixed {
    flex-direction: column;
    gap: 12px;
  }

  .header-actions {
    align-self: flex-end;
  }
}
</style>
